﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplicationMyTest.Models
{
	public class DataManager
	{
		private ItemsListDBEntities _db;

		public DataManager()
		{
			_db = new ItemsListDBEntities();
		}

		public DataManager(ItemsListDBEntities db)
		{
			this._db = db ?? new ItemsListDBEntities();
		}

		public IQueryable<Item> GetItems()
		{
			return _db.Items;
		}

		public Item GetItem(Guid id)
		{
			return _db.Items.SingleOrDefault(item => item.ItemId == id);
		}

		public void SaveItem(Item obj)
		{
			var oldObject = GetItem(obj.ItemId);
			oldObject.Title = obj.Title;
			oldObject.Quantity = obj.Quantity;
			_db.SaveChanges();
		}

		public IQueryable<Category> GetCategories()
		{
			return _db.Categories;
		}

		public Category GetCategory(Guid categoryID)
		{
			return GetCategories().SingleOrDefault(item => item.CategoryId == categoryID);
		}

		public void CreateCategory(Category category)
		{
			if (category == null)
				return;

			if (category.CategoryId == Guid.Empty)
			{
				category.CategoryId = Guid.NewGuid();
			}

			_db.Categories.Add(category);
		}

		public void DeleteCategory(Guid id)
		{
			var category = this.GetCategory(id);
			if (category == null)
				return;

			_db.Categories.Remove(category);
		}

		public void Save()
		{
			_db.SaveChanges();
		}
	}
}